package com.mmall.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

public class PropertiesUtil {
    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static Properties props;

    static {
        String filename = "mmall.properties";
        props = new Properties();
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(
                    PropertiesUtil.class.getClassLoader().getResourceAsStream(filename), "UTF-8");
            props.load(isr);
        } catch (IOException e) {
            logger.error("配置文件读取异常", e);
        } finally {
            try {
                // 课程视频中,流并没有关闭
                // <https://coding.imooc.com/lesson/96.html#mid=3305>
                isr.close();
            } catch (IOException e) {
                logger.error("IO流关闭异常", e);
            }
        }
    }

    public static String getProperty(String key){
        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            return null;
        }
        return value.trim();
    }

    public static String getProperty(String key, String defaultValue){
        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            value = defaultValue;
        }
        return value.trim();
    }
}
